package cn.edu.cug.cs.gtl.oi.ui.actions;

import cn.edu.cug.cs.gtl.oi.ui.MainApp;
import com.openinventor.inventor.SoPreferences;
import com.openinventor.inventor.nodes.SoNode;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

public class OpenH3DFileActionListener implements ActionListener {
    MainApp theApp = null;

    public OpenH3DFileActionListener(MainApp theApp){
        this.theApp = theApp;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        final FileFilter h3dFileFilter = new H3DFileFilter();

        final JFileChooser h3dFileChooser = new JFileChooser(
                new File(SoPreferences.getValue("OIVJHOME") + File.separator + "data" + File.separator + "models"));
        h3dFileChooser.setFileFilter(h3dFileFilter);
        h3dFileChooser.removeChoosableFileFilter(h3dFileChooser.getAcceptAllFileFilter());

        if ( h3dFileChooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION )
            return;
        String fileName = h3dFileChooser.getSelectedFile().getAbsolutePath();
        SoNode node = null;
        try {
            node = theApp.readSceneGraph(fileName);
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
        if(node==null) return;

        theApp.getMainWindow().getRenderPanel().reset(node);
        theApp.getMainWindow().getProjectPanel().reset();
        theApp.getMainWindow().getTablePanel().reset();
    }
}
